﻿package cn.hadron.aa.action.admin;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.*;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.hadron.aa.entity.User;
import cn.hadron.aa.service.*;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@Controller
@Scope("prototype") 
@ParentPackage("admin")
@Namespace("/admin")
public class AdminAction extends ActionSupport {
	private String password0;
	private String password1;
	private User user;
	private String message;// 提示信息
	@Resource(name="userService")
	private UserService us;//Spring注入
	@Action(value="login",results={@Result(name="success",location="/admin/index.jsp"),
				     @Result(name="input",location="/admin/login.jsp")})
	public String login() throws Exception {// 登录
		//首次进入login,返回登录页面
		if (null == user) return LOGIN;
		//再次进入login
		user = us.login(user.getUsername(), user.getPassword());
		if (user != null && user.getRole() == 10) {
			ActionContext.getContext().getSession().put("admin", user);
			message = "登录成功！";
			return SUCCESS;
		} else {
			message = "登录失败！";
			return LOGIN;
		}
	}
	@Action(value="password",
			interceptorRefs={@InterceptorRef("defaultStack"), @InterceptorRef("authority")},
			results={@Result(name="success",location="/admin/success.jsp"),
			         @Result(name="input",location="/admin/password.jsp")})
	public String password() throws Exception {
		Map session=ActionContext.getContext().getSession();
		if(null ==password0 ||null ==password1)
			return INPUT;
		User admin=(User)session.get("admin");
		if(null==us.login(user.getUsername(), user.getPassword())){
			this.addActionError("原有密码错误");
			return INPUT;
		}else{
			us.changePassword(admin.getId(), password1);
			message = "密码修改成功！";
			return SUCCESS;
		}
	}
	@Action(value="exit", results={@Result(name="success",location="/admin/login.jsp")})
	public String exit() throws Exception {
		ActionContext.getContext().getSession().clear();
		System.out.println("退出系统："+ ActionContext.getContext().getSession().get("admin"));
		return SUCCESS;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getPassword0() {
		return password0;
	}

	public void setPassword0(String password0) {
		this.password0 = password0;
	}

	public String getPassword1() {
		return password1;
	}

	public void setPassword1(String password1) {
		this.password1 = password1;
	}

	public UserService getUs() {
		return us;
	}

	public void setUs(UserService us) {
		this.us = us;
	}
}
